<template>
  <div style="width: 100%; height: 100%; padding: 0">
    <div class="page-content" v-if="!showDetail && !showPatientInfo && !showPatientInfoTwo">
      <a-card style="width: 100%; height: 100%">
        <div class="header">
          <template v-if="enterpriseShow">
            <Condition
              :condition="condition"
              :btns="['search', 'reset']"
              @search="searchHandle"
              @reset="reset"
            />
          </template>
          <template v-else>
            <Condition
              :condition="conditionEnterprise"
              :btns="['search', 'reset']"
              @search="searchHandle"
              @reset="reset"
            />
          </template>
          <div class="tabEnterprise">
            <p
              :class="tabEnterpriseDataActive == index ? 'on' : ''"
              v-for="(item, index) in tabEnterpriseData"
              :key="index"
              @click="tabEnterpriseDataCli(item, index)"
            >
              {{ item.name }}
            </p>
          </div>
          <div style="display: flex; align-items: center; justify-content: space-between">
            <a-radio-group
              button-style="solid"
              v-model:value="raidoValue"
              @change="radioValueChange"
            >
              <a-radio-button value="todo">
                {{ tabEnterpriseDataActive == 0 ? '待派单' : '待分配' }}({{
                  dispatchAllCounts ? dispatchAllCounts.noSend : 0
                }})
              </a-radio-button>
              <a-radio-button value="done">
                {{ tabEnterpriseDataActive == 0 ? '已派单' : '已分配' }}({{
                  dispatchAllCounts ? dispatchAllCounts.send : 0
                }})
              </a-radio-button>
            </a-radio-group>
            <div
              v-if="
                (tabEnterpriseDataActive == 1 && raidoValue == 'done') ||
                (tabEnterpriseDataActive == 1 && raidoValue == 'todo' && zhuguanShow == false)
              "
            />
            <div v-else>
              <a-button type="primary" v-if="raidoValue == 'todo'" @click="batchDispatch">{{
                tabEnterpriseDataActive == 0 ? '批量派单' : '批量分配'
              }}</a-button>
              <a-button type="primary" v-else @click="batchTransfer">批量转单</a-button>
            </div>
          </div>
          <!-- <span> 共筛选出 {{ pagination.total }} 条数据 </span> -->
        </div>
        <div class="main">
          <a-table
            class="table"
            size="small"
            :loading="loading"
            :dataSource="List"
            :columns="columns"
            :pagination="pagination"
            @change="paginationChange"
            :sticky="{ offsetHeader: 0 }"
            :rowKey="'id'"
            :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }"
          >
            <!-- <template #bodyCell="{ column, text, record, index }"> -->
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.dataIndex == 'no'">
                {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
              </template>
              <template v-else-if="column.dataIndex === 'patName'">
                <span class="patName" @click="toDetail(record)" type="link">
                  {{ record.patName }} {{ record.gender }} {{ record.age }}
                </span>
              </template>
              <template v-else-if="column.dataIndex === 'unsetNum'">
                <span class="patName" @click="toEnterprise(record)" type="link">
                  {{ record.unsetNum }}
                </span>
              </template>
              <template v-else-if="column.dataIndex === 'setNum'">
                <span class="patName" @click="toEnterprise(record)" type="link">
                  {{ record.setNum }}
                </span>
              </template>
              <template v-else-if="column.dataIndex === 'peOrgType'">
                <span
                  :class="[
                    'peOrgType',
                    record.peOrgType == 0
                      ? 'peOrgType0'
                      : record.peOrgType == 1
                        ? 'peOrgType1'
                        : record.peOrgType == 2
                          ? 'peOrgType2'
                          : 'peOrgType3'
                  ]"
                >
                  {{
                    record.peOrgType == 0
                      ? '独立'
                      : record.peOrgType == 1
                        ? '一级'
                        : record.peOrgType == 2
                          ? '二级'
                          : '三级'
                  }}
                </span>
              </template>
              <template v-else-if="column.dataIndex === 'memberState'">
                <a-tag
                  v-if="record.memberState == '生效中'"
                  style="color: #00b42a; background-color: #e8f7ff; border: 1px solid #00b42a"
                >
                  生效中
                </a-tag>
                <a-tag
                  v-if="record.memberState == '已中止'"
                  style="color: #1d2129; background-color: #f2f3f5; border: 1px solid #1d2129"
                >
                  已中止
                </a-tag>
                <a-tag
                  v-if="record.memberState == '已过期'"
                  style="color: #1d2129; background-color: #f2f3f5; border: 1px solid #1d2129"
                >
                  已过期
                </a-tag>
              </template>
              <template v-else-if="column.dataIndex === 'vipStatus'">
                <a-tag
                  v-if="record.vipStatus == '生效中'"
                  style="color: #00b42a; background-color: #e8f7ff; border: 1px solid #00b42a"
                >
                  生效中
                </a-tag>
                <!-- <a-tag
                  v-if="record.memberState == '已中止'"
                  style="color: #1d2129; background-color: #f2f3f5; border: 1px solid #1d2129"
                >
                  已中止
                </a-tag> -->
                <a-tag
                  v-if="record.vipStatus == '已过期'"
                  style="color: #1d2129; background-color: #f2f3f5; border: 1px solid #1d2129"
                >
                  已过期
                </a-tag>
              </template>

              <template v-else-if="column.dataIndex == 'buyTime'">
                <span v-if="record.buyTime">{{
                  dayjs(record.buyTime).format('YYYY-MM-DD HH:mm')
                }}</span>
                ~
                <span v-if="record.expiredTime">{{
                  dayjs(record.expiredTime).format('YYYY-MM-DD HH:mm')
                }}</span>
              </template>
              <template v-if="column.dataIndex == 'vipStartTime'">
                <span v-if="record.vipStartTime">{{
                  dayjs(record.vipStartTime).format('YYYY-MM-DD HH:mm')
                }}</span>
                ~
                <span v-if="record.expiredTime">{{
                  dayjs(record.expiredTime).format('YYYY-MM-DD HH:mm')
                }}</span>
                <span v-if="record.vipEndTime">{{
                  dayjs(record.vipEndTime).format('YYYY-MM-DD HH:mm')
                }}</span>
              </template>
              <template v-else-if="column.dataIndex === 'questionnaireRecordId'">
                <a-button
                  type="link"
                  :disabled="!record.questionnaireRecordId"
                  @click="questionAnswerForm(record)"
                  >检后问卷</a-button
                >
              </template>
              <!-- <template v-else-if="column.dataIndex === 'questionState'">
                <span style="color: #00b42a" v-if="record.questionState">
                  <CheckCircleFilled two-tone-color="#00B42A" />
                  已填写
                </span>
                <span style="color: #f53f3f" v-if="!record.questionState">
                  <ExclamationCircleFilled two-tone-color="#F53F3F" />
                  未填写
                </span>
              </template> -->
              <template v-else-if="column.dataIndex === 'pathName'">
                <span v-if="record.pathName && raidoValue == 'todo'">{{ record.pathName }}</span>
                <span
                  style="color: #1677ff; cursor: pointer"
                  v-else-if="record.pathName && raidoValue == 'done'"
                  @click="addOrUpdateHandle(record)"
                  type="link"
                >
                  {{ record.pathName }}
                </span>
                <span v-else>/</span>
              </template>
              <template v-else-if="column.dataIndex === 'serviceState'">
                <span style="color: #ff7d00" v-if="record.serviceState == 'TODO'">
                  <ExclamationCircleFilled two-tone-color="#FF7D00" />
                  待执行
                </span>
                <span style="color: #3491fa" v-if="record.serviceState == 'DOING'">
                  <ExclamationCircleFilled two-tone-color="#3491FA" />
                  处理中
                </span>
                <span style="color: #3491fa" v-if="record.serviceState == 'REPROCESSING'">
                  <ExclamationCircleFilled two-tone-color="#3491FA" />
                  处理中
                </span>
                <span style="color: #0fc6c2" v-if="record.serviceState == 'DONE'">
                  <CheckCircleFilled two-tone-color="#0FC6C2" />
                  已推送
                </span>
                <span style="color: #1d2129" v-if="record.serviceState == 'EXPIRED'">
                  <ExclamationCircleFilled two-tone-color="#1d2129" />
                  已过期
                </span>
              </template>

              <template v-else-if="column.dataIndex === 'action'">
                <div
                  v-if="
                    (tabEnterpriseDataActive == 1 && raidoValue == 'done') ||
                    (tabEnterpriseDataActive == 1 && raidoValue == 'todo' && zhuguanShow == false)
                  "
                />
                <a-button
                  v-else-if="raidoValue == 'todo' && tabEnterpriseDataActive == 0"
                  type="link"
                  @click="dispatchHandle(record)"
                  :disabled="record.memberState != '生效中'"
                  >派单</a-button
                >
                <a-button
                  v-else-if="raidoValue == 'done' && tabEnterpriseDataActive == 0"
                  type="link"
                  @click="dispatchHandle(record)"
                  :disabled="record.memberState != '生效中'"
                >
                  转单
                </a-button>
                <a-button
                  v-else
                  type="link"
                  @click="dispatchHandle(record)"
                  :disabled="record.vipStatus != '生效中'"
                >
                  分配团队
                </a-button>
                <a-button
                  v-if="tabEnterpriseDataActive == 1"
                  type="link"
                  @click="toEnterprise(record)"
                  >查看员工</a-button
                >
              </template>
            </template>
          </a-table>
        </div>
      </a-card>

      <a-modal v-model:open="dispatchOpen" :title="dispatchTitle" :mask-closable="false">
        <a-form ref="dispatchFormRef" :model="dispatchForm">
          <a-form-item
            label="选择负责人"
            name="dispatchUserId"
            :rules="[{ required: true, message: '请选择负责人' }]"
          >
            <a-select
              v-model:value="dispatchForm.dispatchUserId"
              style="width: 100%"
              placeholder="请选择负责人"
              showSearch
              :options="managerData"
            />
          </a-form-item>
        </a-form>
        <template #footer>
          <a-button key="back" @click="dispatchOpen = false">取消</a-button>
          <a-button key="submit" type="primary" @click="saveHandle" :loading="dispatchLoading">
            确定
          </a-button>
        </template>
      </a-modal>
      <a-modal v-model:open="dispatchOpenTwo" :title="dispatchTitle" :mask-closable="false">
        <a-form ref="dispatchFormRef" :model="dispatchForm">
          <a-form-item
            label="选择服务团队"
            name="dispatchUserId"
            :rules="[{ required: true, message: '请选择服务团队' }]"
          >
            <a-select
              v-model:value="dispatchForm.dispatchUserId"
              style="width: 100%"
              placeholder="选择服务团队"
              showSearch
              @change="handleChange"
              :options="managerDataTwo"
            >
              <!-- @search="customSearch" -->
              <!-- <a-select-option v-for="item in managerDataTwo" :key="item.value">
                  {{ item.label }} &nbsp; {{ item.leaderName }}组长
                  {{ item.label }}
                </a-select-option> -->
            </a-select>
          </a-form-item>
        </a-form>
        <template #footer>
          <a-button key="back" @click="dispatchOpenTwo = false">取消</a-button>
          <a-button key="submit" type="primary" @click="saveHandle" :loading="dispatchLoading">
            确定
          </a-button>
        </template>
      </a-modal>
    </div>
    <FollowInfo ref="followInfoRef" />
    <ManaPlan ref="manaPlanRef" v-if="showDetail" @close="goBack" />
    <PatientInfo ref="patientInfoRef" v-if="showPatientInfo" @close="gopatientBack" />
    <enterprise ref="patientInfoRefTwo" v-if="showPatientInfoTwo" @closed="gopatientBackTwo" />
  </div>
</template>
<script lang="ts" setup>
import Condition from '@/components/ConditionSearch/index.vue'
import { CheckCircleFilled, ExclamationCircleFilled } from '@ant-design/icons-vue'
import { ref, onMounted, reactive } from 'vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import store from '@/store'
import {
  getDispatchList,
  getManagePlanByDiseaseType,
  getAllUser,
  batchDispatchApi,
  managerPage,
  getMemberpeOrg,
  getAllUserGroup,
  groupPeOrg,
  questionAnswer
} from '@/api/healthManaWorkbench/index'
import { useRoute } from 'vue-router'

const route = useRoute()

import ManaPlan from '../implement/manaPlan.vue'
import PatientInfo from '@/views/examinatePatients/patientInfo.vue'
import enterprise from './enterprise.vue'
import FollowInfo from '@/views/specializedDiseaseWorkbench/dispatch/followInfo.vue'

const showDetail = ref(false)
const showPatientInfo = ref(false)
const showPatientInfoTwo = ref(false)
const loading = ref<boolean>(false)
const List = ref<any[]>([])
const raidoValue = ref('todo')
const state = reactive<{
  selectedRowKeys: Key[]
}>({
  selectedRowKeys: []
})

const managerData: any = ref([])
const managerFormData: any = ref([])
const tabEnterpriseData: any = ref([
  {
    name: '个人',
    value: '1'
  },
  {
    name: '团队',
    value: '2'
  }
])
const tabEnterpriseDataActive = ref(0)
const enterpriseShow = ref(true)
const dispatchAllCounts = ref()
const dispatchOpen = ref(false)
const dispatchOpenTwo = ref(false)
const leaderIdTwo = ref('')
const dispatchTitle = ref('')
const managerDataTwo: any = ref([])
const manaPathData = ref([])
const dispatchForm = reactive({
  dispatchUserId: undefined
})

const conditionTodo = ref([
  {
    title: '会员购买时间',
    dataIndex: 'buyTime',
    type: 'dayRange',
    value: [],
    format: 'YYYY-MM-DD HH:mm',
    showTime: true,
    style: { width: '300px' }
  },
  {
    title: '会员状态',
    dataIndex: 'memberState',
    type: 'select',
    value: undefined,
    placeholder: '请选择会员状态',
    data: [
      {
        label: '生效中',
        value: 1
      },
      {
        label: '已中止',
        value: 4
      },
      {
        label: '已过期',
        value: 8
      }
    ]
  },
  {
    title: '报告生成时间',
    dataIndex: 'visitTime',
    type: 'dayRange',
    value: [],
    format: 'YYYY-MM-DD HH:mm',
    showTime: true,
    style: { width: '300px' }
  },
  {
    title: '',
    dataIndex: 'condition',
    type: 'input',
    value: '',
    placeholder: '请输入姓名/证件号'
  },
  {
    title: '问卷状态',
    dataIndex: 'questionState',
    type: 'select',
    data: [
      {
        label: '未填写',
        value: false
      },
      {
        label: '已填写',
        value: true
      }
    ],
    value: undefined,
    placeholder: '请选择问卷状态'
  },
  {
    title: '管理路径',
    dataIndex: 'pathId',
    type: 'select',
    data: manaPathData.value,
    value: undefined,
    placeholder: '请选择管理路径',
    showSearch: true
  }
])
const conditionDone = ref([
  {
    title: '会员购买时间',
    dataIndex: 'buyTime',
    type: 'dayRange',
    value: [],
    format: 'YYYY-MM-DD HH:mm',
    showTime: true,
    style: { width: '300px' }
  },
  {
    title: '会员状态',
    dataIndex: 'memberState',
    type: 'select',
    value: undefined,
    placeholder: '请选择会员状态',
    data: [
      {
        label: '生效中',
        value: 1
      },
      {
        label: '已中止',
        value: 4
      },
      {
        label: '已过期',
        value: 8
      }
    ]
  },
  {
    title: '报告生成时间',
    dataIndex: 'visitTime',
    type: 'dayRange',
    value: [],
    format: 'YYYY-MM-DD HH:mm',
    showTime: true,
    style: { width: '300px' }
  },
  {
    title: '',
    dataIndex: 'condition',
    type: 'input',
    value: '',
    placeholder: '请输入姓名/证件号'
  },
  {
    title: '',
    dataIndex: 'manager',
    type: 'select',
    value: undefined,
    data: managerFormData.value,
    showSearch: true,
    placeholder: '请输入负责人'
  },
  {
    title: '管理路径',
    dataIndex: 'pathId',
    type: 'select',
    data: manaPathData.value,
    value: undefined,
    placeholder: '请选择管理路径',
    showSearch: true
  },
  {
    title: '问卷状态',
    dataIndex: 'questionState',
    type: 'select',
    data: [
      {
        label: '未填写',
        value: false
      },
      {
        label: '已填写',
        value: true
      }
    ],
    value: undefined,
    placeholder: '请选择问卷状态'
  },
  {
    title: '服务状态',
    dataIndex: 'serviceState',
    type: 'select',
    value: undefined,
    data: [
      {
        label: '待执行',
        value: 'TODO'
      },
      {
        label: '处理中',
        value: 'DOING'
      },
      {
        label: '已推送',
        value: 'DONE'
      }
    ],
    placeholder: '请选择服务状态'
  }
])
const zhuguanShow = ref(false)
const zuzhangShow = ref(false)
const condition = ref()
const conditionEnterprise = ref([])
const conditionTodoTwo = ref([
  {
    title: '',
    dataIndex: 'peOrgName',
    type: 'input',
    value: '',
    placeholder: '请输入企业名称/ID'
  },
  {
    title: '企业类型',
    dataIndex: 'peOrgType',
    type: 'select',
    data: [
      {
        label: '独立',
        value: '0'
      },
      {
        label: '一级',
        value: '1'
      },
      {
        label: '二级',
        value: '2'
      },
      {
        label: '三级',
        value: '3'
      }
    ],
    value: undefined,
    placeholder: '请选择企业类型'
  },
  {
    title: '会员状态',
    dataIndex: 'vipStatus',
    type: 'select',
    value: undefined,
    placeholder: '请选择会员状态',
    data: [
      {
        label: '生效中',
        value: 2
      },
      {
        label: '已过期',
        value: 9
      }
    ]
  },
  {
    title: '会员购买时间',
    dataIndex: 'buyTime',
    type: 'dayRange',
    value: [],
    format: 'YYYY-MM-DD HH:mm',
    showTime: true,
    style: { width: '300px' }
  }
])
const conditionDoneTwo = ref([
  {
    title: '',
    dataIndex: 'peOrgName',
    type: 'input',
    value: '',
    placeholder: '请输入企业名称/ID'
  },
  {
    title: '企业类型',
    dataIndex: 'peOrgType',
    type: 'select',
    data: [
      {
        label: '独立',
        value: '0'
      },
      {
        label: '一级',
        value: '1'
      },
      {
        label: '二级',
        value: '2'
      },
      {
        label: '三级',
        value: '3'
      }
    ],
    value: undefined,
    placeholder: '请选择企业类型'
  },
  {
    title: '会员状态',
    dataIndex: 'vipStatus',
    type: 'select',
    value: undefined,
    placeholder: '请选择会员状态',
    data: [
      {
        label: '生效中',
        value: 2
      },
      {
        label: '已过期',
        value: 9
      }
    ]
  },
  {
    title: '会员购买时间',
    dataIndex: 'buyTime',
    type: 'dayRange',
    value: [],
    format: 'YYYY-MM-DD HH:mm',
    showTime: true,
    style: { width: '300px' }
  }
])
const columnsTodoTwo = ref<any[]>([
  {
    title: '序号',
    dataIndex: 'no',
    key: 'no',
    align: 'left',
    width: 80
  },
  {
    title: '企业ID',
    dataIndex: 'peOrgId',
    key: 'peOrgId',
    align: 'left'
  },
  {
    title: '企业名称',
    dataIndex: 'peOrgName',
    key: 'peOrgName',
    align: 'left'
  },
  {
    title: '企业类型',
    dataIndex: 'peOrgType',
    key: 'peOrgType',
    align: 'left'
  },
  {
    title: '会员状态',
    dataIndex: 'vipStatus',
    key: 'vipStatus',
    align: 'left'
  },
  {
    title: '会员有效期',
    dataIndex: 'vipStartTime',
    key: 'vipStartTime',
    align: 'left',
    width: 150
  },
  {
    title: '会员套餐',
    dataIndex: 'pePackageName',
    key: 'pePackageName',
    align: 'left'
  },
  {
    title: '待分配员工',
    dataIndex: 'unsetNum',
    key: 'unsetNum',
    align: 'left'
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'left'
  }
])

const columnsDoneTwo = ref<any[]>([
  {
    title: '序号',
    dataIndex: 'no',
    key: 'no',
    align: 'left',
    width: 80
  },
  {
    title: '企业ID',
    dataIndex: 'peOrgId',
    key: 'peOrgId',
    align: 'left'
  },
  {
    title: '企业名称',
    dataIndex: 'peOrgName',
    key: 'peOrgName',
    align: 'left'
  },
  {
    title: '企业类型',
    dataIndex: 'peOrgType',
    key: 'peOrgType',
    align: 'left'
  },
  {
    title: '会员状态',
    dataIndex: 'vipStatus',
    key: 'vipStatus',
    align: 'left'
  },
  {
    title: '会员有效期',
    dataIndex: 'vipStartTime',
    key: 'vipStartTime',
    align: 'left',
    width: 150
  },
  {
    title: '会员套餐',
    dataIndex: 'pePackageName',
    key: 'pePackageName',
    align: 'left'
  },
  // {
  //   title: '创建时间',
  //   dataIndex: 'createTime',
  //   key: 'createTime',
  //   align: 'left'
  // },
  {
    title: '服务团队',
    dataIndex: 'groupName',
    key: 'groupName',
    align: 'left'
  },
  {
    title: '服务组长',
    dataIndex: 'groupManagerName',
    key: 'groupManagerName',
    align: 'left'
  },
  {
    title: '已分配员工',
    dataIndex: 'setNum',
    key: 'setNum',
    align: 'left'
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'left',
    width: 100
  }
])

const columns = ref<any[]>([])
const columnsTodo = ref<any[]>([
  {
    title: '序号',
    dataIndex: 'no',
    key: 'no',
    align: 'left',
    width: 80
  },
  {
    title: '账号',
    dataIndex: 'userPhone',
    key: 'userPhone',
    align: 'left'
  },
  {
    title: '患者手机号',
    dataIndex: 'phone',
    key: 'phone',
    align: 'left'
  },
  {
    title: '患者',
    dataIndex: 'patName',
    key: 'patName',
    align: 'left'
  },
  //   {
  //     title: '性别',
  //     dataIndex: 'gender',
  //     key: 'gender',
  //     align: 'left'
  //   },
  //   {
  //     title: '年龄',
  //     dataIndex: 'age',
  //     key: 'age',
  //     align: 'left'
  //   },
  {
    title: '证件号',
    dataIndex: 'idNo',
    key: 'idNo',
    align: 'left'
  },
  {
    title: '会员状态',
    dataIndex: 'memberState',
    key: 'memberState',
    align: 'left'
  },
  {
    title: '会员有效期',
    dataIndex: 'buyTime',
    key: 'buyTime',
    align: 'left',
    width: 150
  },
  {
    title: '会员套餐',
    dataIndex: 'tradeName',
    key: 'tradeName',
    align: 'left'
  },
  {
    title: '报告生成时间',
    dataIndex: 'visitTime',
    key: 'visitTime',
    align: 'left'
  },

  {
    title: '管理路径',
    dataIndex: 'pathName',
    key: 'pathName',
    align: 'left'
  },
  {
    title: '问卷',
    dataIndex: 'questionnaireRecordId',
    key: 'questionnaireRecordId',
    align: 'left',
    width: 100
  },
  // {
  //   title: '问卷状态',
  //   dataIndex: 'questionState',
  //   key: 'questionState',
  //   align: 'left'
  // },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'left',
    width: 100
  }
])

const columnsDone = ref<any[]>([
  {
    title: '序号',
    dataIndex: 'no',
    key: 'no',
    align: 'left',
    width: 80
  },
  {
    title: '账号',
    dataIndex: 'userPhone',
    key: 'userPhone',
    align: 'left'
  },
  {
    title: '患者手机号',
    dataIndex: 'phone',
    key: 'phone',
    align: 'left'
  },
  {
    title: '患者',
    dataIndex: 'patName',
    key: 'patName',
    align: 'left'
  },
  //   {
  //     title: '性别',
  //     dataIndex: 'gender',
  //     key: 'gender',
  //     align: 'left'
  //   },
  //   {
  //     title: '年龄',
  //     dataIndex: 'age',
  //     key: 'age',
  //     align: 'left'
  //   },
  {
    title: '证件号',
    dataIndex: 'idNo',
    key: 'idNo',
    align: 'left'
  },
  {
    title: '会员状态',
    dataIndex: 'memberState',
    key: 'memberState',
    align: 'left'
  },
  {
    title: '会员有效期',
    dataIndex: 'buyTime',
    key: 'buyTime',
    align: 'left',
    width: 150
  },
  {
    title: '会员套餐',
    dataIndex: 'tradeName',
    key: 'tradeName',
    align: 'left'
  },
  {
    title: '报告生成时间',
    dataIndex: 'visitTime',
    key: 'visitTime',
    align: 'left'
  },

  {
    title: '管理路径',
    dataIndex: 'pathName',
    key: 'pathName',
    align: 'left'
  },
  {
    title: '问卷',
    dataIndex: 'questionnaireRecordId',
    key: 'questionnaireRecordId',
    align: 'left',
    width: 100
  },
  // {
  //   title: '问卷状态',
  //   dataIndex: 'questionState',
  //   key: 'questionState',
  //   align: 'left'
  // },
  {
    title: '服务状态',
    dataIndex: 'serviceState',
    key: 'serviceState',
    align: 'left'
  },
  {
    title: '负责人',
    dataIndex: 'managerName',
    key: 'managerName',
    align: 'left'
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'left',
    width: 100
  }
])

const pagination = ref<any>({
  current: 1,
  total: 0,
  pageSize: 10,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100'],
  showQuickJumper: true
})
const paginationChange = (page: any) => {
  pagination.value = { ...page }
  loading.value = true
  getDataList()
}

const onSelectChange = (selectedRowKeys: Key[]) => {
  state.selectedRowKeys = selectedRowKeys
}
const handleChange = (value) => {
  //   leaderIdTwo.value = managerDataTwo.value.filter((item) => {
  //     return item.value == value
  //   }).leaderId
  managerDataTwo.value.forEach((item) => {
    if (item.value == value) {
      leaderIdTwo.value = item.leaderId
    }
  })
  //   console.log('管理', leaderIdTwo.value)
}

const manaPlanRef = ref()
const addOrUpdateHandle = (data) => {
  showDetail.value = true
  nextTick(() => {
    manaPlanRef.value.init(data)
  })
}

const followInfoRef = ref()
const questionAnswerForm = (data) => {
  const params = {
    questionnaireRecordId: data.questionnaireRecordId,
    empi: data.empi
  }

  followInfoRef.value.init(params)
}

const getDataList = () => {
  state.selectedRowKeys = []
  List.value = []
  let obj = {}
  if (tabEnterpriseDataActive.value == 0) {
    obj = condition.value.reduce((c, v) => {
      if (v.value || v.value === 0 || v.value === false) {
        if (v.dataIndex == 'visitTime') {
          return Object.assign(c, {
            visitTimeSta: v.value.length ? dayjs(v.value[0]).format('YYYY-MM-DD HH:mm:00') : '',
            visitTimeEnd: v.value.length ? dayjs(v.value[1]).format('YYYY-MM-DD HH:mm:00') : ''
          })
        } else if (v.dataIndex == 'buyTime') {
          return Object.assign(c, {
            buyTimeSta: v.value.length ? dayjs(v.value[0]).format('YYYY-MM-DD HH:mm:00') : '',
            buyTimeEnd: v.value.length ? dayjs(v.value[1]).format('YYYY-MM-DD HH:mm:00') : ''
          })
        } else {
          return Object.assign(c, { [v.dataIndex]: v.value })
        }
      } else {
        return c
      }
    }, {})
    getDispatchList({
      ...obj,
      serviceState: obj.serviceState ? [obj.serviceState] : [],
      page: pagination.value.current,
      limit: pagination.value.pageSize,
      isSet: raidoValue.value == 'todo' ? false : true,
      chose: true
    })
      .then((res) => {
        dispatchAllCounts.value = res.data
        List.value = res.data.page.list
        pagination.value.total = res.data.page.total
        loading.value = false

        List.value = [...List.value]
      })
      .catch(() => {
        loading.value = false
      })
  } else {
    obj = conditionEnterprise.value.reduce((c, v) => {
      if (v.value || v.value === 0 || v.value === false) {
        if (v.dataIndex == 'visitTime') {
          return Object.assign(c, {
            visitTimeSta: v.value.length ? dayjs(v.value[0]).format('YYYY-MM-DD HH:mm:00') : '',
            visitTimeEnd: v.value.length ? dayjs(v.value[1]).format('YYYY-MM-DD HH:mm:00') : ''
          })
        } else if (v.dataIndex == 'buyTime') {
          return Object.assign(c, {
            begin: v.value.length ? dayjs(v.value[0]).format('YYYY-MM-DD HH:mm:00') : '',
            end: v.value.length ? dayjs(v.value[1]).format('YYYY-MM-DD HH:mm:00') : ''
          })
        } else {
          return Object.assign(c, { [v.dataIndex]: v.value })
        }
      } else {
        return c
      }
    }, {})
    managerPage({
      ...obj,
      workOrderState: raidoValue.value == 'todo' ? '待派单' : '已派单',
      serviceState: obj.serviceState ? [obj.serviceState] : [],
      page: pagination.value.current,
      limit: pagination.value.pageSize,
      isManager: zhuguanShow.value,
      isLeader: zuzhangShow.value
      //   chose: true
    })
      .then((res) => {
        dispatchAllCounts.value = res.data
        List.value = res.data.page.list
        pagination.value.total = res.data.page.total
        loading.value = false

        List.value = [...List.value]
      })
      .catch(() => {
        loading.value = false
      })
  }
}
onMounted(async () => {
  if (store.userApp.permissionList.indexOf('eprofile:pe:zhuguan') != -1) {
    zhuguanShow.value = true
  } else {
    zhuguanShow.value = false
  }
  if (store.userApp.permissionList.indexOf('eprofile:pe:zuzhang') != -1) {
    zuzhangShow.value = true
  } else {
    zuzhangShow.value = false
  }
  if (route.query && route.query.type === 'manaPlan') {
    showDetail.value = true
    nextTick(() => {
      manaPlanRef.value.init({
        ...route.query,
        empi: route.query.empi,
        userId: route.query.id
      })
    })
  }
  leaderIdTwo.value = ''
  managerData.value = []
  managerFormData.value = []
  loading.value = true
  columns.value = []
  condition.value = conditionTodo.value
  await getManaPath()
  await getAllUserGroupFun()
  await getAllUser().then(async (res) => {
    managerData.value = []
    res.data.forEach((item) => {
      managerData.value.push({
        value: item.id,
        label: item.realName + ' ' + item.workerCategory + ' ' + item.mobile
      })

      managerFormData.value.push({
        value: item.id,
        label: item.realName
      })
    })

    conditionDone.value[4].data = managerFormData.value
    conditionDone.value = [...conditionDone.value]
  })

  columns.value = [...columns.value, ...columnsTodo.value]
  getDataList()
})

const getManaPath = async () => {
  await getManagePlanByDiseaseType({
    diseaseType: 'checkAfter'
  }).then((res) => {
    if (res.data && res.data.length > 0) {
      res.data.map((item) => {
        item.label = item.managePathName
        item.value = item.id
      })
      manaPathData.value = res.data
    } else {
      manaPathData.value = []
    }
    conditionTodo.value[5].data = manaPathData.value
    conditionDone.value[5].data = manaPathData.value
  })
}
const getAllUserGroupFun = async () => {
  await getAllUserGroup({}).then((res) => {
    managerDataTwo.value = []
    res.data.forEach((item) => {
      if (item.groupName) {
        managerDataTwo.value.push({
          value: item.groupId,
          label: item.groupName + '  ' + item.leaderName + '组长',
          leaderName: item.leaderName,
          leaderId: item.leaderId
        })
      }
    })
  })
}

const groupPeOrgFun = async () => {
  await groupPeOrg({}).then((res) => {
    managerDataTwo.value = []
    res.data.forEach((item) => {
      if (item.groupName) {
        managerDataTwo.value.push({
          value: item.groupId,
          label: item.groupName + '  ' + item.leaderName + '组长',
          leaderName: item.leaderName,
          leaderId: item.leaderId
        })
      }
    })
  })
}
// 个人和企业切换
const tabEnterpriseDataCli = (item, index) => {
  // tabEnterpriseDataCli
  conditionEnterprise.value = []
  condition.value = []
  columns.value = []
  if (index == 0) {
    getAllUserGroupFun()
    enterpriseShow.value = true
    if (raidoValue.value == 'todo') {
      columns.value = [...columns.value, ...columnsTodo.value]
      condition.value = [...condition.value, ...conditionTodo.value]
    } else {
      columns.value = [...columns.value, ...columnsDone.value]
      condition.value = [...condition.value, ...conditionDone.value]
    }
  } else {
    groupPeOrgFun()
    enterpriseShow.value = false
    if (raidoValue.value == 'todo') {
      columns.value = [...columns.value, ...columnsTodoTwo.value]
      conditionEnterprise.value = [...conditionEnterprise.value, ...conditionTodoTwo.value]
    } else {
      columns.value = [...columns.value, ...columnsDoneTwo.value]
      conditionEnterprise.value = [...conditionEnterprise.value, ...conditionDoneTwo.value]
    }
  }
  tabEnterpriseDataActive.value = index
  reset()
}
// 查看员工
const patientInfoRefTwo = ref()
const toEnterprise = (data) => {
  showPatientInfoTwo.value = true
  nextTick(() => {
    patientInfoRefTwo.value.initRouterInfo(
      data,
      raidoValue.value,
      tabEnterpriseDataActive.value,
      zuzhangShow.value
    )
  })
}

// 患者详情
const patientInfoRef = ref()
const toDetail = (data) => {
  showPatientInfo.value = true
  nextTick(() => {
    patientInfoRef.value.initRouterInfo(data)
  })
}

const searchHandle = () => {
  pagination.value.current = 1
  loading.value = true
  getDataList()
}
const reset = () => {
  managerFormData.value = []
  pagination.value.current = 1
  pagination.value.pageSize = 10
  getManaPath()

  getAllUser().then((res) => {
    managerData.value = []
    res.data.forEach((item) => {
      managerData.value.push({
        value: item.id,
        label: item.realName + ' ' + item.workerCategory + ' ' + item.mobile
      })

      managerFormData.value.push({
        value: item.id,
        label: item.realName
      })
    })

    conditionDone.value[4].data = managerFormData.value
    conditionDone.value = [...conditionDone.value]
  })

  condition.value.map((v) => {
    if (v.type === 'select') {
      v.value = undefined
    } else if (v.type === 'dayRange') {
      v.value = []
    } else {
      v.value = ''
    }
  })
  conditionEnterprise.value.map((v) => {
    if (v.type === 'select') {
      v.value = undefined
    } else if (v.type === 'dayRange') {
      v.value = []
    } else {
      v.value = ''
    }
  })
  loading.value = true
  getDataList()
}

const isDispatchData: any = ref([])

const dispatchFormRef = ref()
// 批量派单
const batchDispatch = () => {
  isDispatchData.value = []
  if (state.selectedRowKeys.length) {
    if (tabEnterpriseDataActive.value == 0) {
      dispatchOpenTwo.value = false
      dispatchOpen.value = true
    } else {
      dispatchOpenTwo.value = true
      dispatchOpen.value = false
    }
    dispatchTitle.value = '批量派单'
    dispatchForm.dispatchUserId = undefined
    isDispatchData.value = List.value.filter((item) => {
      return state.selectedRowKeys.includes(item.id)
    })
  } else {
    message.warning('请选择需要派单的记录')
  }
}
// 批量转单
const batchTransfer = () => {
  isDispatchData.value = []
  if (state.selectedRowKeys.length) {
    dispatchOpen.value = true
    dispatchTitle.value = '批量转单'
    dispatchForm.dispatchUserId = undefined
    isDispatchData.value = List.value.filter((item) => {
      return state.selectedRowKeys.includes(item.id)
    })
  } else {
    message.warning('请选择需要转单的记录')
  }
}

// 单条记录操作
const dispatchHandle = (data) => {
  isDispatchData.value = [data]
  dispatchForm.dispatchUserId = undefined
  if (tabEnterpriseDataActive.value == 0) {
    dispatchOpenTwo.value = false
    dispatchOpen.value = true
  } else {
    dispatchOpenTwo.value = true
    dispatchOpen.value = false
  }
  if (raidoValue.value == 'todo') {
    dispatchTitle.value = '派单'
  } else {
    dispatchTitle.value = '转单'
  }
}

const dispatchLoading = ref(false)
// 派单 转单操作
const saveHandle = () => {
  dispatchFormRef.value.validate().then(() => {
    if (tabEnterpriseDataActive.value == 0) {
      isDispatchData.value.forEach((item) => {
        item.manager = dispatchForm.dispatchUserId
        item.scenesActionType = raidoValue.value === 'todo' ? 'DISPATCH_ORDER' : 'CONVERT_ORDER'
      })
      dispatchLoading.value = true
      batchDispatchApi(isDispatchData.value)
        .then((res) => {
          dispatchLoading.value = false
          message.success(`${raidoValue.value === 'todo' ? '派单' : '转单'}成功`)
          dispatchOpen.value = false
          if (raidoValue.value === 'todo') {
            searchHandle()
          } else {
            loading.value = true
            getDataList()
          }
        })
        .catch(() => {
          dispatchLoading.value = false
        })
    } else {
      const obj = {
        manager: leaderIdTwo.value,
        groupId: dispatchForm.dispatchUserId,
        peOrgIds: isDispatchData.value.map((item) => {
          return item.peOrgId
        })
      }
      dispatchLoading.value = true
      getMemberpeOrg(obj)
        .then((res) => {
          dispatchLoading.value = false
          message.success(`${raidoValue.value === 'todo' ? '派单' : '转单'}成功`)
          dispatchOpenTwo.value = false
          if (raidoValue.value === 'todo') {
            searchHandle()
          } else {
            loading.value = true
            getDataList()
          }
        })
        .catch(() => {
          dispatchLoading.value = false
        })
    }
  })
}

const radioValueChange = (e) => {
  columns.value = []
  condition.value = []
  conditionEnterprise.value = []
  if (tabEnterpriseDataActive.value == 0) {
    if (e.target.value == 'done') {
      columns.value = [...columns.value, ...columnsDone.value]
      condition.value = [...condition.value, ...conditionDone.value]
    } else {
      columns.value = [...columns.value, ...columnsTodo.value]
      condition.value = [...condition.value, ...conditionTodo.value]
    }
  } else {
    if (e.target.value == 'done') {
      state.selectedRowKeys = []
      columns.value = [...columns.value, ...columnsDoneTwo.value]
      conditionEnterprise.value = [...conditionEnterprise.value, ...conditionDoneTwo.value]
    } else {
      columns.value = [...columns.value, ...columnsTodoTwo.value]
      conditionEnterprise.value = [...conditionEnterprise.value, ...conditionTodoTwo.value]
    }
  }

  reset()
}

const goBack = () => {
  showDetail.value = false
  loading.value = true
  getDataList()
}

const gopatientBack = () => {
  showPatientInfo.value = false
  loading.value = true
  getDataList()
}
const gopatientBackTwo = () => {
  showPatientInfoTwo.value = false
  loading.value = true
  getDataList()
}
</script>
<style lang="less" scoped>
.header {
  display: flex;
  justify-content: space-between;

  .tabEnterprise {
    position: relative;
    margin-bottom: 16px;

    p {
      display: inline-block;
      width: 60px;
      height: 32px;
      margin: 0;
      margin-right: 4px;
      font-size: 14px;
      line-height: 32px;
      color: #4e5969;
      text-align: center;
      vertical-align: middle;
      background: #f7f8fa;
      border: 1px solid #e5e6eb;
      border-top-left-radius: 2px;
      border-top-right-radius: 2px;

      &.on {
        position: relative;
        z-index: 1;
        font-weight: 700;
        color: #165dff;
        background: #fff;
        border-bottom: 0;
      }

      &:hover {
        cursor: pointer;
        opacity: 0.8;
      }
    }

    &::after {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      content: '';
      border-bottom: 1px solid #e5e6eb;
    }
  }
}

.main {
  flex: 1 1 auto;
  margin-top: 16px;
  overflow: hidden auto;

  .patName {
    color: #1677ff;

    &:hover {
      cursor: pointer;
      opacity: 0.7;
    }
  }

  .peOrgType {
    padding: 2px 7px;
    font-size: 12px;
    color: #f7ba1e;
    background: #fffce8;
    border: 1px solid #f7ba1e;
    border-radius: 2px;

    &.peOrgType0 {
      color: #00b42a;
      background: #e8ffea;
      border-color: #00b42a;
    }

    &.peOrgType1 {
      color: #3491fa;
      background: #e8f7ff;
      border-color: #3491fa;
    }

    &.peOrgType2 {
      color: #0fc6c2;
      background: #e8fffb;
      border-color: #0fc6c2;
    }
  }
}

.page-content {
  padding: 16px;
}
</style>
